package com.ai.txyun.deepseek;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class DeepSeekApiClient {
    private static final String API_URL = "https://api.deepseek.com/chat/completions";
    private final String apiKey;

    public DeepSeekApiClient(String apiKey) {
        this.apiKey = apiKey;
    }

    public String callDeepSeekApi(String userMessage) throws Exception {
        // 构建请求体JSON
        String requestBody = String.format("""
        {
            "model": "deepseek-chat",
            "messages": [
                {"role": "system", "content": "You are a helpful assistant."},
                {"role": "user", "content": "%s"}
            ],
            "stream": false
        }
        """, escapeJson(userMessage));

        // 创建HTTP连接
        URL url = new URL(API_URL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Authorization", "Bearer " + apiKey);
        connection.setDoOutput(true);

        // 发送请求
        try (OutputStream os = connection.getOutputStream()) {
            byte[] input = requestBody.getBytes(StandardCharsets.UTF_8);
            os.write(input, 0, input.length);
        }

        // 读取响应
        try (BufferedReader br = new BufferedReader(
                new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
            StringBuilder response = new StringBuilder();
            String responseLine;
            while ((responseLine = br.readLine()) != null) {
                response.append(responseLine.trim());
            }
            return response.toString();
        }
    }

    // 简单的JSON转义方法
    private String escapeJson(String input) {
        return input.replace("\\", "\\\\")
                .replace("\"", "\\\"")
                .replace("\n", "\\n")
                .replace("\r", "\\r")
                .replace("\t", "\\t");
    }

    public static void main(String[] args) {
        String apiKey = "your-api-key-here"; // 替换为你的实际API密钥
        DeepSeekApiClient client = new DeepSeekApiClient(apiKey);

        try {
            String response = client.callDeepSeekApi("Hello!");
            System.out.println("API Response: " + response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}